package com.qinghong.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Component
public class UserService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    PlatformTransactionManager transactionManager;

    @Autowired
    TransactionTemplate transactionTemplate;

    public void transfer(){
        // 定义默认的事务属性 获取TransactionStatus
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            jdbcTemplate.update("update user set money = ? where username = ?",9,"zhangsan");
            // 提交事务
            int i = 10/0;
            transactionManager.commit(status);
        } catch (DataAccessException e) {
            e.printStackTrace();
            transactionManager.rollback(status);
        }
    }

    public void transfer3(){
        jdbcTemplate.update("update user set money = ? where username = ?",9,"zhangsan");
//        int i = 1/0;
    }

    // 开启xml注解
    @Transactional(isolation = Isolation.DEFAULT)
    public void transfer4(){
        jdbcTemplate.update("update user set money = ? where username = ?",9,"zhangsan");
//        int i = 1/0;
    }

    public void transfer2(){
//        transactionTemplate.setIsolationLevel();
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    jdbcTemplate.update("update user set money = ? where username = ?",9,"zhangsan");
                    // 提交事务
//                    int i = 10/0;
                } catch (DataAccessException e) {
                    // 设置当前事务回滚
                    status.setRollbackOnly();
                    e.printStackTrace();
                }
            }
        });
    }
}
